package com.myapp.ruyixing.ui;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.Volley;
import com.myapp.ruyixing.R;
import com.myapp.ruyixing.http.RYHttpClient;
import com.myapp.ruyixing.http.RYHttpResponseHandler;
import com.myapp.ruyixing.model.ShopAlbum;
import com.myapp.ruyixing.model.ShopAlbum.PhotoItem;
import com.myapp.ruyixing.model.ShopAlbum.ShopSubAlbum;
import com.myapp.ruyixing.ui.widget.TitleBar;
import com.myapp.ruyixing.utils.BitmapLruCache;

public class ShopAlbumActivity extends BaseActivity implements OnClickListener,
		OnItemClickListener {

	private GridView mGridView;
	private TextView mEmptyView;
	private View mLoadingView;
	private LinearLayout mTabsView;

	private View mFocusedTabView;

	private String mShopId;
	private String mShopName;

	private String mCurrTypeId;

	private List<ShopSubAlbum> mTopAlbums;

	private RYHttpResponseHandler mTopHandler = new RYHttpResponseHandler() {

		@Override
		public void onSuccess(Object o) {
			ShopAlbum data = (ShopAlbum) o;

			if (data != null && data.data != null) {
				mTopAlbums = data.data;
				setTabs();

				if (mTabsView.getChildCount() > 0) {
					TextView firstTab = (TextView) mTabsView.getChildAt(0);
					changeTab(firstTab);
				}
				mLoadingView.setVisibility(View.GONE);
			}
		}

		@Override
		public void onFailure(Throwable throwable) {
			if (!isFinishing()) {
				Toast.makeText(getApplicationContext(), "加载失败",
						Toast.LENGTH_SHORT).show();
			}
		}
	};

	private RYHttpResponseHandler mTypeHandler = new RYHttpResponseHandler() {

		@Override
		public void onSuccess(Object o) {
			ShopSubAlbum data = (ShopSubAlbum) o;

			if (data != null && data.items != null) {
				MyListAdapter adapter = new MyListAdapter(
						(ArrayList<PhotoItem>) data.items);
				mGridView.setAdapter(adapter);
			}
			mGridView.setEmptyView(mEmptyView);

			mLoadingView.setVisibility(View.GONE);
		}

		@Override
		public void onFailure(Throwable throwable) {
			if (!isFinishing()) {
				Toast.makeText(getApplicationContext(), "加载失败",
						Toast.LENGTH_SHORT).show();
			}
		}
	};

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);

		setContentView(R.layout.activity_shop_album);

		initView();

		mShopId = getIntent().getStringExtra(ShopDetailActivity.INTENT_SHOP_ID);
		mShopName = getIntent().getStringExtra(
				ShopDetailActivity.INTENT_SHOP_NAME);
		if (TextUtils.isEmpty(mShopId) == true) {
			Toast.makeText(getApplicationContext(), "商户为空", Toast.LENGTH_SHORT)
					.show();
		} else {
			mLoadingView.setVisibility(View.VISIBLE);
			RYHttpClient.getShopTopAlbum(this, mTopHandler, mShopId);
		}

		if (TextUtils.isEmpty(mShopName) == false) {
			((TitleBar) findViewById(R.id.title_bar)).setTitleText("相册\n"
					+ mShopName);
		}
	}

	@Override
	public void onClick(View v) {
		changeTab(v);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		PhotoItem item = (PhotoItem) mGridView.getAdapter().getItem(position);

		if (TextUtils.isEmpty(item.typeid) == false) {
			startActivity(new Intent(this, ShopSubAlbumActivity.class)
					.putExtra(ShopDetailActivity.INTENT_SHOP_ID, mShopId)
					.putExtra(ShopDetailActivity.INTENT_SHOP_NAME, mShopName)
					.putExtra("title", item.title)
					.putExtra("typeid", item.typeid));
		} else if (TextUtils.isEmpty(item.photoid) == false) {
			startActivity(new Intent(this, ShopBigAlbumActivity.class)
					.putExtra(ShopDetailActivity.INTENT_SHOP_ID, mShopId)
					.putExtra(ShopDetailActivity.INTENT_SHOP_NAME, mShopName)
					.putExtra("title", item.title)
					.putExtra("typeid", mCurrTypeId)
					.putExtra("position", position)
					.putExtra("photos",
							((MyListAdapter) mGridView.getAdapter()).mData));
		}
	}

	private void changeTab(View v) {
		if (mFocusedTabView == v) {
			return;
		}

		if (mFocusedTabView != null) {
			mFocusedTabView.setSelected(false);
		}
		mFocusedTabView = v;
		mFocusedTabView.setSelected(true);

		String name = ((TextView) v).getText().toString();
		if ("全部".equals(name)) {
			mCurrTypeId = getTypeId(name);
			MyListAdapter adapter = new MyListAdapter(
					(ArrayList<PhotoItem>) getAllPhotos());
			mGridView.setAdapter(adapter);
		} else {
			requestSubData(name);
		}
	}

	private void requestSubData(String name) {
		String id = getTypeId(name);
		if (TextUtils.isEmpty(id) == false) {
			mCurrTypeId = id;

			mLoadingView.setVisibility(View.VISIBLE);
			RYHttpClient.getShopTypeAlbum(ShopAlbumActivity.this, mTypeHandler,
					mShopId, id);
		}
	}

	private void setTabs() {
		for (int i = 0; i < mTabsView.getChildCount(); i++) {
			TextView tabView = (TextView) mTabsView.getChildAt(i);
			if (i < mTopAlbums.size()) {
				ShopSubAlbum subAlbum = mTopAlbums.get(i);
				tabView.setText(subAlbum.name);
			} else {
				tabView.setVisibility(View.GONE);
			}
		}

		for (int i = 0; i < mTabsView.getChildCount(); i++) {
			mTabsView.getChildAt(i).setOnClickListener(this);
		}
	}

	private String getTypeId(String name) {
		if (mTopAlbums != null) {
			for (ShopSubAlbum album : mTopAlbums) {
				if (name.equals(album.name)) {
					return album.typeid;
				}
			}
		}

		return null;
	}

	private List<PhotoItem> getAllPhotos() {
		if (mTopAlbums != null) {
			for (ShopSubAlbum album : mTopAlbums) {
				if ("全部".equals(album.name)) {
					return album.items;
				}
			}
		}

		return null;
	}

	private void initView() {
		mGridView = (GridView) findViewById(R.id.gridview);
		mEmptyView = (TextView) findViewById(android.R.id.empty);
		mLoadingView = findViewById(R.id.my_loading);
		mTabsView = (LinearLayout) findViewById(R.id.tabs);

		mGridView.setOnItemClickListener(this);

		((TitleBar) findViewById(R.id.title_bar))
				.setOnIconClickedListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						onBackPressed();
					}
				});

		((TitleBar) findViewById(R.id.title_bar))
				.setOnRightIconClickedListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						startActivity(new Intent(ShopAlbumActivity.this,
								UploadPhotoActivity.class).putExtra(
								ShopDetailActivity.INTENT_SHOP_ID, mShopId)
								.putExtra(ShopDetailActivity.INTENT_SHOP_NAME,
										mShopName));

					}
				});
	}

	private class ViewHolder {
		TextView mNameView;
		TextView mPriceView;
		NetworkImageView mShopImage;
		TextView mRecommendView;
	}

	private class MyListAdapter extends ArrayAdapter<PhotoItem> {

		private RequestQueue mQueue;
		private ImageLoader mImageLoader;
		ArrayList<PhotoItem> mData;

		public MyListAdapter(ArrayList<PhotoItem> list) {
			super(ShopAlbumActivity.this, -1, list);
			mData = list;
			mQueue = Volley.newRequestQueue(ShopAlbumActivity.this);
			mImageLoader = new ImageLoader(mQueue, new BitmapLruCache());
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = LayoutInflater.from(getContext()).inflate(
						R.layout.cell_shop_album, parent, false);

				ViewHolder holder = new ViewHolder();
				holder.mNameView = (TextView) convertView
						.findViewById(R.id.text_name);
				holder.mPriceView = (TextView) convertView
						.findViewById(R.id.text_price);
				holder.mRecommendView = (TextView) convertView
						.findViewById(R.id.text_recommend);
				holder.mShopImage = (NetworkImageView) convertView
						.findViewById(R.id.picture);

				convertView.setTag(holder);
			}

			ViewHolder holder = (ViewHolder) convertView.getTag();
			PhotoItem item = getItem(position);

			holder.mNameView.setText(item.title);
			holder.mPriceView.setText(item.price);
			if (!TextUtils.isEmpty(item.score)) {
				holder.mRecommendView.setText(item.score + "人推荐");
			} else {
				holder.mRecommendView.setVisibility(View.INVISIBLE);
			}
			if (!TextUtils.isEmpty(item.picurl)) {
				holder.mShopImage.setImageUrl(item.picurl, mImageLoader);
			}

			return convertView;

		}
	}
}
